package com.ziyun.erp.modules.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.common.constant.OrderSplitType;
import com.service.goods.api.GoodsService;
import com.service.goods.constant.GoodsResult;
import com.service.goods.model.goods.BaseGoodsInfoVO;
import com.service.goods.model.goods.BasePriceDetail;
import com.service.goods.model.goods.MultyErpOrderParam;
import com.service.order.api.MallErpOrderService;
import com.service.order.constant.OrderResult;
import com.service.order.model.erp.AllotOrderResultDto;
import com.service.order.model.erp.ErpAllotFactoryOrderParamDto;
import com.service.quote.module.factory.model.FactoryInfoVO;
import com.service.quote.module.factory.model.FactoryQuoteInfo;
import com.service.quote.module.quote.model.QuoteResult;
import com.utility.DateUtils;
import com.utility.StringUtils;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.e.order.*;
import com.ziyun.erp.common.e.production.AllotTypeEnum;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.e.production.ProducerTypeEnum;
import com.ziyun.erp.common.e.supp.StateEnum;
import com.ziyun.erp.common.utils.ErpOrderUtils;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.modules.goods.entity.GoodsEntity;
import com.ziyun.erp.modules.goodsCategory.entity.GoodsCategoryEntity;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryRelationService;
import com.ziyun.erp.modules.goodsCategory.service.GoodsCategoryService;
import com.ziyun.erp.modules.member.entity.*;
import com.ziyun.erp.modules.member.service.*;
import com.ziyun.erp.modules.order.dao.ErpOrderDao;
import com.ziyun.erp.modules.order.dto.*;
import com.ziyun.erp.modules.order.entity.*;
import com.ziyun.erp.modules.order.vo.*;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.ErpOrderStateContext;
import com.ziyun.erp.modules.production.operate.WaitAllotState;
import com.ziyun.erp.modules.production.operate.WaitProducingState;
import com.ziyun.erp.modules.production.operate.entity.AllotStateEntity;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import com.ziyun.erp.modules.production.vo.ErpOrderAllotVo;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.vo.ErpOrderItemListVo;
import com.ziyun.erp.modules.production.vo.ErpOrderProductionListVo;
import com.ziyun.erp.modules.quoteParts.entity.QuotePartsEntity;
import com.ziyun.erp.modules.quoteParts.service.QuotePartsService;
import com.ziyun.erp.modules.quoteProduct.service.QuoteProductBaseInfoService;
import com.ziyun.erp.modules.store.storeGoodsProduct.entity.StoreGoodsProductEntity;
import com.ziyun.erp.modules.store.storeGoodsProduct.service.StoreGoodsProductService;
import com.ziyun.erp.modules.store.storeProductPrice.service.StoreProductPriceService;
import com.ziyun.erp.modules.store.storeProductPrice.vo.StoreProductPriceVo;
import com.ziyun.erp.modules.supp.entity.SellerInfoEntity;
import com.ziyun.erp.modules.supp.service.SellerInfoService;
import com.ziyun.erp.modules.suppOffline.entity.ErpSupplierOfflineEntity;
import com.ziyun.erp.modules.suppOffline.service.ErpSupplierOfflineService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;
import com.service.common.constant.GoodsSplitType;

@Slf4j
@Service("erpOrderService")
public class ErpOrderServiceImpl extends ServiceImpl<ErpOrderDao, ErpOrderEntity> implements ErpOrderService {

    @Autowired
    private SynOrderRecordService synOrderRecordService;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ErpOrderItemService erpOrderItemService;
    @Autowired
    private UserPaymentService userPaymentService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private GoodsCategoryRelationService goodsCategoryRelationService;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private UserBaseInfoService userBaseInfoService;
    @Autowired
    private UserOrderCommissionService userOrderCommissionService;
    @Autowired
    private UserShareService userShareService;
    @Autowired
    private OrderRemarksService orderRemarksService;
    @Autowired
    private ErpOrderProductionService erpOrderProductionService;
    @Autowired
    private QuoteProductBaseInfoService quoteProductBaseInfoService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private QuotePartsService quotePartsService;
    @Autowired
    private StoreGoodsProductService storeGoodsProductService;
    @Autowired
    private StoreProductPriceService storeProductPriceService;
    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private ErpSupplierOfflineService erpSupplierOfflineService;
    @Autowired
    private MallErpOrderService mallErpOrderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserAccessoryService userAccessoryService;
    @Autowired
    private ErpOrderAllotRelevanceService erpOrderAllotRelevanceService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private UserScholarshipService userScholarshipService;
    @Autowired
    private com.ziyun.erp.modules.goods.service.GoodsService erpGoodsService;
    @Autowired
    private OrderTaxService orderTaxService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public R queryPageErpOrderList(Map<String, Object> params) {
        // 默认查询全部订单
        int totalCount = this.baseMapper.countErpOrder(params);

        int current = Integer.valueOf((String) params.get("page"));
        int size = Integer.valueOf((String) params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<ErpOrderAllotVo> list = this.baseMapper.queryPageErpOrderList(params);

        // 存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("productionStatusEnum", JsonUtils.enumToList(ProductionStatusEnum.class));
        mapEnum.put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class));

        R r = R.ok();
        r.put("page", new PageUtils(list, totalCount, size, current));
        r.put("userData", mapEnum);
        return r;
    }

    @Override
    public R queryPage(Map<String, Object> params) {
        Page<ErpOrderEntity> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<ErpOrderEntity> list = this.baseMapper.getErpOrderEntityList(page, params);
        page.setRecords(list);
        PageUtils pageUtils = new PageUtils(page);
        // 存放枚举类到userdata
        Map<String, Object> mapEnum = new HashMap<>();
        mapEnum.put("paymentEnum", JsonUtils.enumToList(PaymentEnum.class)); //支付方式集合
        return R.ok().put("page", pageUtils).put("userData", mapEnum);
    }

    @Override
    public ErpOrderEntity selectByNo(String orderNo) {
        return this.selectOne(new EntityWrapper<ErpOrderEntity>().eq("order_no", orderNo));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synProductionOrder(List<OrderInfoEntity> list) {
        for (OrderInfoEntity orderInfoEntity : list) {

            ErpOrderEntity erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            if (erpOrderEntity == null) {
                String msg = "订单号：" + orderInfoEntity.getOrderId() + "同步失败";
                log.info(msg);
                continue;
            }

            // 判断订单是否已同步
            ErpOrderEntity erpOrderEntityCheck = this.selectOne(new EntityWrapper<ErpOrderEntity>().eq("order_no", erpOrderEntity.getOrderNo()));
            if (erpOrderEntityCheck != null)
                continue;

            baseMapper.insert(erpOrderEntity);

            /******************************* 同步订单商品 start *******************************/
            List<OrderItemEntity> orderItemList = orderItemService.selectList(
                    new EntityWrapper<OrderItemEntity>()
                            .eq("order_id", orderInfoEntity.getOrderId()));
            if (orderItemList == null || orderItemList.size() == 0) {
                String msg = "订单号：" + orderInfoEntity.getOrderId() + " , 未查询到订单商品明细";
                log.info(msg);
            } else {
                List<ErpOrderItemEntity> erpOrderItemList = ErpOrderUtils.ziyunOrderItemToErp(orderItemList, erpOrderEntity.getOrderNo());

                if (orderItemList.size() != erpOrderItemList.size()) {
                    throw new RRException("订单商品同步数量异常");
                }
                erpOrderItemService.insertBatch(erpOrderItemList);
            }
            /******************************* 同步订单商品 end  ********************************/

            // 订单同步记录表
            SynOrderRecord synOrderRecord = new SynOrderRecord();
            synOrderRecord.setErpOrder(erpOrderEntity.getOrderNo());
            synOrderRecord.setOrderId("" + orderInfoEntity.getOrderId());
            synOrderRecord.setSource(1); //订单来源：紫云网

            synOrderRecordService.insert(synOrderRecord);
        }
    }

    @Override
    public ErpOrderEntity selectByOrderId(Long orderId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("original_order_id", orderId);
        param.put("del", 0);
        List<ErpOrderEntity> erpOrderEntities = this.baseMapper.selectByMap(param);
        if (erpOrderEntities.size() == 0) {
            return null;
        }
        return erpOrderEntities.get(0);
    }

    @Override
    public ErpOrderVo selectErpOrderVoByOrderId(Long orderId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("orderId", orderId);
        List<ErpOrderVo> erpOrderVos = this.baseMapper.selectErpOrderVoByOrderId(param);
        if (erpOrderVos.size() == 0) {
            return null;
        }
        return erpOrderVos.get(0);
    }

    @Override
    public String selectOrderNoByOrderId(Long orderId) {
        return this.baseMapper.selectOrderNoByOrderId(orderId);
    }

    /**
     * 同步紫云网订单支付信息
     *
     * @param orderInfoList
     */
    @Override
    public void synOrderPayInfo(List<OrderInfoEntity> orderInfoList) {
        for (OrderInfoEntity orderInfoEntity : orderInfoList) {
            //erp订单
            ErpOrderEntity erpOrderEntity = this.selectByOrderId(Long.parseLong(orderInfoEntity.getOrderId()));

            Map updateMap = new HashMap<>();
            // 已支付
            if ("1".equals(orderInfoEntity.getPayStatus())) {
                UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderInfoEntity.getOrderId());

                if (userPayment == null) {
                    log.info("支付信息获取异常！");
                    throw new RRException("未查询到支付信息！");
                }
                updateMap.put("payStatus", 1);
                updateMap.put("paymentTime", userPayment.getTPayed());
                updateMap.put("payment", userPayment.getPayName());
                updateMap.put("paymentId", userPayment.getPaymentId());
                baseMapper.updateByMap(updateMap, erpOrderEntity.getOrderNo());
            } else {
                log.info("订单号：" + orderInfoEntity.getOrderId() + " ；支付状态：" + orderInfoEntity.getPayStatus());
            }
        }
    }

    /**
     * 同步紫云网订单确认收货信息
     *
     * @param orderInfoList
     */
    @Override
    public void synOrderReceiveInfo(List<OrderInfoEntity> orderInfoList) {
        for (OrderInfoEntity orderInfoEntity : orderInfoList) {
            if (!orderInfoEntity.getReceivedStatus())
                continue;
            //erp订单
            ErpOrderEntity erpOrderEntity = this.selectByOrderId(Long.parseLong(orderInfoEntity.getOrderId()));
            if (erpOrderEntity == null)
                continue;

            Map updateMap = new HashMap<>();
            updateMap.put("receivedStatus", 1);
            updateMap.put("receivedTime", orderInfoEntity.getReceivedTime());
            updateMap.put("productionStatus", ProductionStatusEnum.FINISH.toInt());
            baseMapper.updateByMap(updateMap, erpOrderEntity.getOrderNo());

            // 订单日志
            erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(), "同步紫云网订单确认收货状态");

        }
    }

    /**
     * 同步紫云网订单取消信息
     *
     * @param orderInfoList
     */
    @Override
    public void synOrderCancleInfo(List<OrderInfoEntity> orderInfoList) {
        for (OrderInfoEntity orderInfoEntity : orderInfoList) {
            if (!"dead".equals(orderInfoEntity.getStatus()))
                continue;
            //erp订单
            ErpOrderEntity erpOrderEntity = this.selectByOrderId(Long.parseLong(orderInfoEntity.getOrderId()));
            if (erpOrderEntity == null)
                continue;

            Map updateMap = new HashMap<>();
            updateMap.put("productionStatus", ProductionStatusEnum.CANCELLED.toInt());
            baseMapper.updateByMap(updateMap, erpOrderEntity.getOrderNo());

            // 订单日志
            erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(), "同步紫云网订单取消状态");
        }
    }

    @Override
    public void updateByMap(Map<String, Object> map, String orderNo) {
        baseMapper.updateByMap(map, orderNo);
    }

//    @Override
//    public Page<ErpOrderEntity> selectNotSendConfirmPage(Page<ErpOrderEntity> page) {
//        List<ErpOrderEntity> list = baseMapper.selectNotSendConfirmPage(page);
//        return page.setRecords(list);
//    }

    /**
     * 未计算佣金订单列表
     *
     * @param page
     * @return
     */
    @Override
    public Page<ErpOrderEntity> selectNotCalculateCommissionPage(Page<ErpOrderEntity> page) {
        List<ErpOrderEntity> list = baseMapper.selectNotCalculateCommissionPage(page);
        return page.setRecords(list);
    }

    /**
     * 佣金计算
     *
     * @param erpOrderEntityList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculateCommission(List<ErpOrderEntity> erpOrderEntityList) {
        for (ErpOrderEntity erpOrderEntity : erpOrderEntityList) {
            log.info(erpOrderEntity.getOrderNo());
            if (!(erpOrderEntity.getThirdMerchantType() == 0 && erpOrderEntity.getOrderSource() == 1)) {//中浩紫云、紫云网
                continue;
            } else if (erpOrderEntity.getShareStatus() != 0) { // 是否已计算
                continue;
            }

            // 查看是否有推荐会员
            log.info("" + erpOrderEntity.getMemberId());
            UserBaseInfoEntity userBaseInfoEntity = userBaseInfoService.selectReferralsMember(erpOrderEntity.getMemberId());
            if (userBaseInfoEntity != null) {
                // 佣金
                BigDecimal commission = new BigDecimal(0);
                // 订单支付总额 - 运费
                BigDecimal orderPayed = erpOrderEntity.getPayed().subtract(erpOrderEntity.getCostFreight());
                // 商品总额
                BigDecimal itemTotal = erpOrderItemService.selectItemTotalMoney(erpOrderEntity.getOrderNo());

                List<ErpOrderItemEntity> erpOrderItemEntityList = erpOrderItemService.selectListByErpOrder(erpOrderEntity.getOrderNo());
                for (int i = 0; i < erpOrderItemEntityList.size(); i++) {
                    ErpOrderItemEntity erpOrderItemEntity = erpOrderItemEntityList.get(i);
                    // 所属分类 佣金计算信息
                    BigDecimal commissionRatio = goodsCategoryRelationService.getCommissionByGoodsId(erpOrderItemEntity.getGoodsId());
                    if (commissionRatio == null || commissionRatio.doubleValue() <= 0.0) {
                        continue;
                    }
                    commissionRatio = commissionRatio.setScale(3, BigDecimal.ROUND_HALF_UP);
                    // 开启佣金计算:   商品佣金 =  （商品售价/商品总额）* (订单支付总额 - 运费)* 佣金分成比例
                    commission = commission.add(erpOrderItemEntity.getAmount()
                            .divide(itemTotal, 5, BigDecimal.ROUND_HALF_UP)
                            .multiply(orderPayed)
                            .multiply(commissionRatio));
                }
                // 保存佣金记录
                if (commission.doubleValue() > 0) {
                    UserOrderCommissionEntity userOrderCommissionEntity = new UserOrderCommissionEntity();
                    userOrderCommissionEntity.setCommission(commission);
                    userOrderCommissionEntity.setOrderId(erpOrderEntity.getOriginalOrderId());
                    userOrderCommissionEntity.setUserId(erpOrderEntity.getMemberId());
                    userOrderCommissionEntity.setOrderAmount(erpOrderEntity.getPayed());
                    userOrderCommissionEntity.setSUserId(userBaseInfoEntity.getUserId());
                    userOrderCommissionEntity.setStatus(1);
                    userOrderCommissionService.insert(userOrderCommissionEntity);

                    // 用户佣金总额
                    UserShareEntity userShareEntity = userShareService.selectById(userOrderCommissionEntity.getSUserId());
                    if (userShareEntity == null) {
                        userShareEntity = new UserShareEntity();
                        userShareEntity.setUserId(userOrderCommissionEntity.getSUserId());
                        userShareEntity.setTotalCommission(userOrderCommissionEntity.getCommission());
                        userShareEntity.setFreezeCommission(userOrderCommissionEntity.getCommission());
                        userShareService.insert(userShareEntity);
                    } else {
                        boolean bool = userShareService.updateCommissionAdd(userOrderCommissionEntity.getSUserId()
                                , userOrderCommissionEntity.getCommission(), userShareEntity.getUsableCommission());
                        if (!bool) {
                            String msg = "订单号：" + erpOrderEntity.getOrderNo() + " 佣金计算失败！";
                            throw new RRException(msg);
                        }
                    }
                }
            }

            Map<String, Object> erpOrderMap = new HashMap<>();
            erpOrderMap.put("shareStatus", 1); // 已结算
            erpOrderService.updateByMap(erpOrderMap, erpOrderEntity.getOrderNo());
        }
    }

    @Override
    public List<ErpOrderEntity> queryListByProductionId(List<String> productionIds) {
        return baseMapper.queryListByProductionId(productionIds);
    }

    /**
     * 财务确认订单付款
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R receiveConfrim(FinanceReceiveMoneyDto financeReceiveMoneyDto) {
        String orderNo = financeReceiveMoneyDto.getOrderNo();
        if (StringUtils.isBlank(orderNo)) {
            return R.error("没有订单号信息");
        }

        String[] split = orderNo.split(",");
        List<String> ids = Arrays.asList(split);
        List<ErpOrderEntity> erpOrderEntities = this.selectBatchIds(ids);

        long count = erpOrderEntities.stream().filter(item -> item.getPayStatus().intValue() != 1).count();
        if (count > 0) {
            return R.error("存在订单号未支付");
        }
        count = erpOrderEntities.stream().filter(item -> item.getReceiveMoneyDate() != null).count();
        if (count > 0) {
            return R.error("存在订单号已收款");
        }

        BigDecimal receiveMoney = financeReceiveMoneyDto.getReceiveMoney();
        Date receiveMoneyDate = financeReceiveMoneyDto.getReceiveMoneyDate();
        String receiveMoneyRemark = financeReceiveMoneyDto.getReceiveMoneyRemark();
        Integer batch = financeReceiveMoneyDto.getIsBatch();
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("receiveMoneyDate", receiveMoneyDate);
        if (StringUtil.isNotEmpty(receiveMoneyRemark)) {
            updateMap.put("receiveMoneyRemark", receiveMoneyRemark.trim());
        }
        if (batch.intValue() == 1) {
            this.baseMapper.receiveMonryBatch(updateMap, ids);

            for (ErpOrderEntity erpOrder : erpOrderEntities) {
                String no = erpOrder.getOrderNo();
                UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderNo);
                String payAppId = userPayment.getPayAppId();
                if (payAppId.equals(PayTypeEnum.CREDIT.toCode())) {
                    BigDecimal payed = erpOrder.getPayed();
                    Integer memberId = erpOrder.getMemberId();
                    userWalletService.recoveryCredit(payed, no, memberId);
                }
            }

        } else {
            updateMap.put("receiveMoney", receiveMoney);
            this.baseMapper.updateByMap(updateMap, orderNo);

            // 信用支付订单返还信用额度
            UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderNo);
            String payAppId = userPayment.getPayAppId();
            if (payAppId.equals(PayTypeEnum.CREDIT.toCode())) {
                ErpOrderEntity erpOrderEntity = erpOrderEntities.get(0);
                Integer memberId = erpOrderEntity.getMemberId();
                userWalletService.recoveryCredit(receiveMoney, orderNo, memberId);
            }
        }

        for (String orderId : ids) {
            erpOrderLogService.insertOrderLog(orderId, "财务确认收款");
        }

        return R.ok();
    }


    /*
    修改收款信息
     */
    @Override
    @Transactional
    public R updateDialogForm(FinanceReceiveMoneyDto financeReceiveMoneyDto, SysUserEntity curentUser) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("receiveMoneyDate", financeReceiveMoneyDto.getReceiveMoneyDate());
        updateMap.put("receiveMoneyRemark", financeReceiveMoneyDto.getReceiveMoneyRemark().trim());

        Integer batch = financeReceiveMoneyDto.getIsBatch();

        if (batch == 1) {//批量
            String orderNo = financeReceiveMoneyDto.getOrderNo();
            String[] split = orderNo.split(",");
            List<String> ids = Arrays.asList(split);
            this.baseMapper.updateDialogFormBatch(updateMap, ids);
        } else {
            this.baseMapper.updateByMap(updateMap, financeReceiveMoneyDto.getOrderNo());
        }
        //记录操作日志
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setOrderNo(financeReceiveMoneyDto.getOrderNo());
        erpOrderLogEntity.setCreateBy(String.valueOf(curentUser.getUserId()));
        erpOrderLogEntity.setCreateName(curentUser.getUsername());
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setLogText("财务修改收款信息");
        erpOrderLogService.insert(erpOrderLogEntity);
        return R.ok();
    }

    /**
     * 财务确认订单付款备注
     *
     * @param orderNo
     * @param receiveMoneyRemark
     * @return
     */
    @Override
    public R receiveRemark(String orderNo, String receiveMoneyRemark) {
        ErpOrderEntity erpOrderEntity = this.selectByNo(orderNo);
        if (erpOrderEntity == null) {
            return R.error("订单获取异常！");
        } else if (erpOrderEntity.getPayStatus() == PayStatusEnum.ALREADY_PAY_1.toInt()) {
            return R.error("当前订单未支付！");
        } else if (StringUtil.isEmpty(receiveMoneyRemark)) {
            return R.error("备注为空！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("receiveMoneyRemark", receiveMoneyRemark.trim());
        erpOrderService.updateByMap(map, orderNo);

        erpOrderLogService.insertOrderLog(orderNo, "财务确认订单付款备注修改");

        return R.ok();
    }

    /**
     * 财务订单计入成本统计
     *
     * @param orderNo
     * @param costRecord
     * @return
     */
    @Override
    public R costRecordConfirm(String orderNo, Integer costRecord) {
        ErpOrderEntity erpOrderEntity = this.selectByNo(orderNo);
        if (erpOrderEntity == null) {
            return R.error("订单获取异常！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("costRecord", costRecord);
        erpOrderService.updateByMap(map, orderNo);

        erpOrderLogService.insertOrderLog(orderNo, "财务订单计入成本统计");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrder(OrderAllotDto orderAllotDto) {
        AllotStateEntity allotState = new AllotStateEntity();
        allotState.setOrderNo(orderAllotDto.getOrderNo());
        allotState.setProducer(orderAllotDto.getProducer());
        allotState.setCsId(orderAllotDto.getCsId());
        allotState.setPmcId(orderAllotDto.getPmcId());
        allotState.setCost(orderAllotDto.getCost());
        allotState.setSelf(orderAllotDto.getSelf());
        allotState.setIsStandard(orderAllotDto.getIsStandard());
        allotState.setAllotType(AllotTypeEnum.ORDER.toCode());
        allotState.setCsRemark(orderAllotDto.getCsRemark());
        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitAllotState(), allotState);
            R allot = erpOrderStateContext.allot();
            int code = (int) allot.get("code");
            if (code == 500) {
                return allot;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrderItem(OrderItemAllotDto orderItemAllotDto) {
        AllotStateEntity allotStateEntity = new AllotStateEntity();
        allotStateEntity.setErpItemId(orderItemAllotDto.getErpItemId());
        allotStateEntity.setCsId(orderItemAllotDto.getCsId());
        allotStateEntity.setPmcId(orderItemAllotDto.getPmcId());
        allotStateEntity.setProducer(orderItemAllotDto.getProducer());
        allotStateEntity.setOrderNo(orderItemAllotDto.getOrderNo());
        allotStateEntity.setCost(orderItemAllotDto.getCost());
        allotStateEntity.setPrice(orderItemAllotDto.getPrice());
        allotStateEntity.setAllotType(AllotTypeEnum.GOODS.toCode());
        allotStateEntity.setUserId(orderItemAllotDto.getUserId());
        allotStateEntity.setSellerType(orderItemAllotDto.getSellerType());
        allotStateEntity.setSelf(orderItemAllotDto.getSelf());
        allotStateEntity.setCsRemark(orderItemAllotDto.getCsRemark());
        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitAllotState(), allotStateEntity);
            R allot = erpOrderStateContext.allot();
            int code = (int) allot.get("code");
            if (code == 500) {
                return allot;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }

        return R.ok();
    }

    @Override
    public R allotInfo(String orderNo) {
        // 订单信息
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderNo);
        // 订单发票信息
        OrderTaxEntity orderTax = orderTaxService.selectOne(new EntityWrapper<>(new OrderTaxEntity()).eq("order_id", orderNo));
        // ERP订单信息
        ErpOrderVo erpOrderVo = erpOrderService.selectErpOrderVoByOrderId(Long.valueOf(orderNo));
        // 商品列表
        List<ErpOrderItemListVo> erpOrderItemListVoList = erpOrderItemService.selectListByOrderId(orderNo);
        // 附件信息
        for (int i = 0; i < erpOrderItemListVoList.size(); i++) {
            ErpOrderItemListVo erpOrderItemListVo = erpOrderItemListVoList.get(i);
            Integer originalItemId = erpOrderItemListVo.getOriginalItemId();
            if (originalItemId != null) {
                List<UserAccessoryVo> userAccessoryVos = userAccessoryService.queryListByItemId(originalItemId.toString());
                erpOrderItemListVo.setAccessoryCount(userAccessoryVos.size());
            }
        }

        // 查询客服
        List<ErpCustomerServieceUserEntity> csIdList = erpOrderService.getCsOrPmcList(1);
        // 客服ID
        String csId = erpOrderVo.getCsId();
        if (StringUtils.isNotBlank(csId)){
            this.findUserId(csId, csIdList);
        }

        // 查询跟单员
        List<ErpCustomerServieceUserEntity> pmcIdList = erpOrderService.getCsOrPmcList(2);
        // 跟单员ID
        String pmcId = erpOrderVo.getPmcId();
        if (StringUtils.isNotBlank(pmcId)){
            this.findUserId(pmcId, pmcIdList);
        }

        // 客服备注
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderNo);
        List<OrderRemarksVo> remarkList = orderRemarksService.selectOrderRemarksVosByMap(params);
        // 已分配列表
        params.clear();
        params.put("orderNo", orderNo);
        params.put("del", DeleteEnum.NOT_DELETE.toInt());
        List<ErpOrderProductionListVo> erpOrderProductionList = erpOrderProductionService.queryProductionList(params);
        // 支付信息
        Long parentOrderId = orderInfo.getParentOrderId();
        String relId = parentOrderId == null ? orderNo : parentOrderId.toString();
        List<UserPaymentEntity> userPaymentEntities = userPaymentService.queryOrderPaymentInfo(relId);
        return R.ok().put("orderInfo", orderInfo)
                .put("orderTax", orderTax)
                .put("erpOrder", erpOrderVo)
                .put("csIdList", csIdList)
                .put("pmcIdList", pmcIdList)
                .put("remarkList", remarkList)
                .put("erpOrderItemEntityList", erpOrderItemListVoList)
                .put("goodsTypeEnum", JsonUtils.enumToList(GoodsTypeEnum.class))
                .put("taxTypeEnum", JsonUtils.enumToList(TaxTypeEnum.class))
                .put("erpOrderProductionList", erpOrderProductionList)
                .put("userPaymentList", userPaymentEntities);
    }

    /**
     * 查询客服或是跟单员列表是否包含原有数据，若不包含则添加进集合显示
     * @param userId
     * @param list
     */
    public void findUserId(String userId, List<ErpCustomerServieceUserEntity> list){
        boolean findId = false;
        for (ErpCustomerServieceUserEntity entity: list){
            Long uid = entity.getUserId();
            if (StringUtils.equals(uid.toString(), userId)){
                findId = true;
                break;
            }
        }
        if (!findId){
            SysUserEntity sysUserEntity = sysUserService.selectById(userId);
            if (sysUserEntity != null){
                ErpCustomerServieceUserEntity entity = new ErpCustomerServieceUserEntity();
                entity.setUserId(Long.valueOf(userId));
                entity.setUsername(sysUserEntity.getUsername());
                entity.setDisabled(true);
                list.add(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteAllotItem(Integer productionId, String orderId) {
        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitProducingState(), productionId);
            R cancleAllot = erpOrderStateContext.cancleAllot();
            int code = (int) cancleAllot.get("code");
            if (code == 500) {
                return cancleAllot;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }

        erpOrderLogService.insertOrderItemLog(orderId, Long.valueOf(productionId), "生产单信息删除：productionId：" + productionId);

        return R.ok();
    }

    @Override
    public boolean cancelOrderAllotInfo(String orderNo) {
        int update = this.baseMapper.cancelOrderAllotInfo(orderNo);
        if (update == 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrderCrafts(OrderCraftsDto orderCraftsDto) {
        List<OrderCraftQuoteDto> orderCraftQuoteList = orderCraftsDto.getOrderCraftQuoteList();
        List<OrderCraftServerDto> orderCraftServerList = orderCraftsDto.getOrderCraftServerList();
        if (orderCraftQuoteList.size() == 0 && orderCraftServerList.size() == 0) {
            return R.error("未提交分配工序信息");
        }

        AllotStateEntity allotState = new AllotStateEntity();
        allotState.setAllotType(AllotTypeEnum.PROCEDURE.toCode());
        allotState.setOrderCraftQuoteList(orderCraftQuoteList);
        allotState.setOrderCraftServerList(orderCraftServerList);
        allotState.setCsId(orderCraftsDto.getCsId());
        allotState.setPmcId(orderCraftsDto.getPmcId());
        allotState.setOrderNo(orderCraftsDto.getOrderNo());
        allotState.setErpItemId(orderCraftsDto.getErpItemId());

        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitAllotState(), allotState);
            R allot = erpOrderStateContext.allot();
            int code = (int) allot.get("code");
            if (code == 500) {
                return allot;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }


        return R.ok();
    }

    /**
     * 标品分配至自营门店，查询紫云网配价工厂是否配置关联SKU产品，若配置，价格作为自营门店分配价格，注意
     * 阶梯价与广告物料，需要额外计算价格；
     * 分配至第三方，查询所有三方工厂信息，不包含自营门店
     */
    @Override
    public R orderItemAllotFindFactory(Integer itemId, Integer sellerType) {
        OrderItemEntity orderItem = orderItemService.selectById(itemId);
        Long orderId = orderItem.getOrderId();
        Integer productId = orderItem.getProductId();
        if (sellerType == 1) {
            // 标品，查询门店配置价格信息(价格先以紫云工厂配置价格为准)
            List<StoreGoodsProductEntity> storeGoodsProductList = storeGoodsProductService.selectList(new EntityWrapper<>(new StoreGoodsProductEntity())
                    .eq("orig_product_id", productId)
                    .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
            );
            if (storeGoodsProductList.size() == 0) {
                return R.error("未查询到自营门店上架此商品");
            }
            List<Integer> productIds = storeGoodsProductList.stream().map(StoreGoodsProductEntity::getProductId).collect(Collectors.toList());
            Map<String, Object> params = new HashMap<>();
            params.put("productIds", productIds);
            List<StoreProductPriceVo> storeProductPriceVos = storeProductPriceService.selectStoreProductPriceVoList(params);
            List<StoreProductPriceVo> storeProductPriceVoList = storeProductPriceVos.stream()
                    .filter((item) -> item.getSellerId().intValue() == ErpOrderStateContext.ZIYUN_FACTORY_ID.intValue())
                    .collect(Collectors.toList());
            if (storeProductPriceVoList.size() == 0) {
                return R.error("商品未配置价格");
            }
            StoreProductPriceVo storeProductPriceVo = storeProductPriceVoList.get(0);
            BigDecimal price = storeProductPriceVo.getPrice();
            BigDecimal nums = orderItem.getNums();

            // 查询是否有阶梯价
            String stepPrice = storeProductPriceVo.getStepPrice();
            if (StringUtils.isNotBlank(stepPrice)) {
                BigDecimal sprice = calculateStepPrice(stepPrice, nums);
                if (sprice != null) {
                    price = sprice;
                }
            }
            BigDecimal amount = price.multiply(nums);

            // 查询是否广告物料商品
            String goodsType = orderItem.getGoodsType();
            if (goodsType.equals(GoodsTypeEnum.MATERIAL.toCode())) {
                Long goodsId = orderItem.getGoodsId();
                String addon = orderItem.getAddon();
                BigDecimal aprice = calculateMaterialGoodsPrice(goodsId, addon, amount);
                if (aprice != null) {
                    amount = aprice;
                }
            }

            List<OrderItemAllotResultVo> resultList = orderItemAllotToSelfMerchant(price, amount, amount);
            return R.ok().put("factoryInfosQuery", resultList);
        } else {
            log.info("================= standard item find factory api start==================");
            MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
            multyErpOrderParam.setAllotOrderId(orderId.toString());
            multyErpOrderParam.setGoodsSplitType(GoodsSplitType.standardGoods);
            multyErpOrderParam.setOrderItemId(itemId);
            multyErpOrderParam.setOrderSplitType(OrderSplitType.ziyun_net);
            log.info("================= standard item find factory api param：" + JsonUtils.object2String(multyErpOrderParam));
            GoodsResult<?> goodsForOrderErp = goodsService.getGoodsForOrderErp(multyErpOrderParam);
            int code = goodsForOrderErp.getCode();
            if (code != 1) {
                String message = goodsForOrderErp.getMessage();
                if (code == 999) {
                    log.info("================= standard item find factory api error：" + message);
                    throw new RRException("派单服务异常，请联系后台管理员");
                }
                return R.error(message);
            }

            String result = JsonUtils.object2String(goodsForOrderErp.getData());
            List<BaseGoodsInfoVO> goodsInfoVOList = (List<BaseGoodsInfoVO>) JsonUtils.queryJsonToList(result, BaseGoodsInfoVO.class);
//            List<BaseGoodsInfoVO> goodsInfoVOList = (List<BaseGoodsInfoVO>) goodsForOrderErp.getData();
            for (BaseGoodsInfoVO baseGoodsInfoVO : goodsInfoVOList){
                BasePriceDetail basePriceDetail = baseGoodsInfoVO.getBasePriceDetail();
                BigDecimal totalPrice = basePriceDetail.getTotalPrice();
                BigDecimal multiply = totalPrice.multiply(orderItem.getNums());
                basePriceDetail.setTotalPrice(multiply);
            }
            return R.ok().put("factoryStandardInfosQuery", goodsInfoVOList);
        }
    }

    public BigDecimal calculateStepPrice(String stepPrice, BigDecimal nums) {
        BigDecimal price = null;
        StepPriceVo[] stepPriceVos = JsonUtils.string2Array(stepPrice, StepPriceVo.class);
        if (stepPriceVos.length > 0) {
            for (StepPriceVo stepPriceVo : stepPriceVos) {
                BigDecimal minSum = stepPriceVo.getMinSum();
                BigDecimal maxSum = stepPriceVo.getMaxSum();
                int compareMin = nums.compareTo(minSum);
                int compareMax = nums.compareTo(maxSum);
                if (compareMin >= 0 && compareMax < 0) {
                    price = stepPriceVo.getPrice();
                    break;
                }
            }
        }
        return price;
    }

    public BigDecimal calculateMaterialGoodsPrice(Long goodsId, String addon, BigDecimal price) {
        GoodsEntity goods = erpGoodsService.selectById(goodsId);
        Integer categoryId = goods.getCategoryId();
        GoodsCategoryEntity goodsCategory = goodsCategoryService.selectById(categoryId);
        Integer pricingManner = goodsCategory.getPricingManner();
        BigDecimal amount = BigDecimal.ZERO;
        if (pricingManner.intValue() != 2){
            String regex = "\\d+[*]\\d+";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(addon);
            if (matcher.find()) {
                String group = matcher.group();
                String[] split = group.split("\\*");
                BigDecimal len = new BigDecimal(split[0]).divide(BigDecimal.valueOf(1000));
                BigDecimal width = new BigDecimal(split[1]).divide(BigDecimal.valueOf(1000));
                if (pricingManner.intValue() == 0){
                    // 按面积计 ( 长 * 宽 ) * 单价 * 数量，不足一平方米按一平方米算
                    BigDecimal area = len.multiply(width);
                    if (area.compareTo(BigDecimal.ONE) < 0) {
                        area = BigDecimal.ONE;
                    }
                    amount = area.multiply(price);
                }else {
                    // 按周长计价 ( 长 + 宽 ) * 2 * 单价 * 数量，不足一米按一米算
                    BigDecimal perimeter = len.add(width).multiply(BigDecimal.valueOf(2));
                    if (perimeter.compareTo(BigDecimal.ONE) < 0) {
                        perimeter = BigDecimal.ONE;
                    }
                    amount = perimeter.multiply(price);
                }
            }
        }else {
            // 按长度计价 长 * 单价 * 数量
            String[] split = addon.split("\\*");
            String s = split[split.length - 1];
            String regEx = "(\\d+(\\.\\d+)?)";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(s);
            if (m.find()){
                String group = m.group();
                amount = new BigDecimal(group).multiply(price);
            }
        }
        return amount;
    }

    /**
     * 查询订单用于成本审核
     *
     * @param params
     * @return
     */
    @Override
    public R queryOrderCostPage(Map<String, Object> params) {
        Map<String, Object> resultMap = this.baseMapper.countCostOrder(params);
        Integer totalCount = Integer.valueOf(resultMap.get("count").toString());
        int current = Integer.valueOf((String) params.get("page"));
        int size = Integer.valueOf((String) params.get("limit"));
        params.put("offset", (current - 1) * size);
        params.put("limit", size);
        List<ErpOrderCostVo> list = this.baseMapper.queryOrderCostPage(params);
        List<Integer> sids = new ArrayList<>();
        sids.add(1);// 紫云网
        sids.add(18); // 阳逻工厂
        sids.add(20);// 配价工厂
        List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_state", StateEnum.IS_AUDITED.toCode())
                .eq("self", 1)
                .notIn("seller_id", sids)
        );
        // 存放枚举类到userdata
        Map<String, Object> mapEnum = new HashMap<>();
        mapEnum.put("productionStatusEnum", JsonUtils.enumToList(ProductionStatusEnum.class));
        mapEnum.put("sellerInfoList", sellerInfoList);
        mapEnum.put("commissionStatusEnum", JsonUtils.enumToList(CommissionStatusEnum.class));
        mapEnum.put("sumTotal", resultMap);
        return R.ok().put("page", new PageUtils(list, totalCount, size, current)).put("userData", mapEnum);
    }

    //门店提成计算订单详情
    @Override
    public R costOrderDetail(String orderNo) {

        R re = R.ok();
        // 订单信息
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderNo);
        //处理数据用于前台展示
        re.put("erpOrder", erpOrder);

        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.selectList(
                new EntityWrapper<ErpOrderItemEntity>()
                        .eq("order_no", orderNo)
                        .eq("item_del", 0)
        );
        re.put("orderItemDetailData", orderItemDetailData);
        //查询商品分配列表

        // 已分配列表
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("del", DeleteEnum.NOT_DELETE.toInt());
        List<ErpOrderProductionListVo> erpOrderProductionList = erpOrderProductionService.queryProductionList(params);
        re.put("erpOrderProductionList", erpOrderProductionList);

        //查询物流列表
        List<OrderLogisticsEntity> orderLogisticsList = orderLogisticsService.selectByOrderNo(orderNo);
        re.put("orderLogisticsList", orderLogisticsList);
        return re;
    }

    //成本审核
    @Override
    public R batchAudit(String ids, String createName, String createBy) {
        Map<String, Object> map = new HashMap<>();
        String[] split = ids.split(",");
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            idList.add(split[i]);
        }
        List<ErpOrderEntity> erpOrderEntities = this.selectBatchIds(idList);
        //判断是否所有订单都为已完成
        for (int i = 0; i < erpOrderEntities.size(); i++) {
            if (erpOrderEntities.get(i).getCommissionStatus() != CommissionStatusEnum.Entered.toInt()) {
                return R.error("请检查所选订单成本状态是否均已录入完成!");
            }
        }
        map.put("commissionStatus", CommissionStatusEnum.SETTLED.toInt());
        this.baseMapper.batchAudit(map, idList);
        //添加订单日志
        List<ErpOrderLogEntity> orderLogEntityList = new ArrayList<>();
        for (int i = 0; i < idList.size(); i++) {
            String orderNo = idList.get(i);
            ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(createBy);
            erpOrderLogEntity.setCreateName(createName);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("erp批量审核");
            orderLogEntityList.add(erpOrderLogEntity);
        }
        if (orderLogEntityList.size() > 0) {
            erpOrderLogService.insertBatch(orderLogEntityList);
        }
        return R.ok();
    }

    @Override
    public R auditCost(String orderNo, String createName, String createBy) {
        ErpOrderEntity erpOrderEntity = this.selectByNo(orderNo);
        if (erpOrderEntity == null) {
            return R.error("查询订单失败!联系管理员!");
        }
        if (erpOrderEntity.getCommissionStatus() != CommissionStatusEnum.Entered.toInt()) {
            return R.error("请选择成本录入完成的订单进行审核!");
        }
        erpOrderEntity.setCommissionStatus(CommissionStatusEnum.SETTLED.toInt());
        this.updateById(erpOrderEntity);
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateBy(createBy);
        erpOrderLogEntity.setCreateName(createName);
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogEntity.setLogText("erp成本审核");
        erpOrderLogService.insert(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    public R reBackStatus(String orderNo, String createName, String createBy) {
        ErpOrderEntity erpOrderEntity = this.selectByNo(orderNo);
        ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
        if (erpOrderEntity == null) {
            return R.error("查询订单失败!联系管理员!");
        }
        if (erpOrderEntity.getCommissionStatus() == CommissionStatusEnum.NOTENTERED.toInt()) {
            return R.error("成本未录入完成订单无法进行撤回!");
        }
        if (erpOrderEntity.getCommissionStatus() == CommissionStatusEnum.SETTLED.toInt()) {
            erpOrderEntity.setCommissionStatus(CommissionStatusEnum.Entered.toInt());
            erpOrderLogEntity.setLogText("erp订单提成审核,状态由已结算撤回到已录入状态");
        } else {
            erpOrderEntity.setCommissionStatus(CommissionStatusEnum.NOTENTERED.toInt());
            erpOrderLogEntity.setLogText("erp订单提成审核,状态由已录入撤回到未录入状态");
        }
        this.updateById(erpOrderEntity);
        erpOrderLogEntity.setOrderNo(orderNo);
        erpOrderLogEntity.setCreateBy(createBy);
        erpOrderLogEntity.setCreateName(createName);
        erpOrderLogEntity.setCreateTime(new Date());
        erpOrderLogService.insert(erpOrderLogEntity);
        return R.ok();
    }

    @Override
    public R batchEnter(String ids, String createName, String createBy) {
        Map<String, Object> map = new HashMap<>();
        String[] split = ids.split(",");
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            idList.add(split[i]);
        }
        List<ErpOrderEntity> erpOrderEntities = this.selectBatchIds(idList);
        //判断是否所有订单都为已完成
        for (int i = 0; i < erpOrderEntities.size(); i++) {
            if (erpOrderEntities.get(i).getProductionStatus() != ProductionStatusEnum.FINISH.toInt()) {
                return R.error("请检查所选订单生产状态是否均为已完成状态!只有已完成才能进行成本录入");
            }
        }
        //判断是否所有订单都为已完成
        for (int i = 0; i < erpOrderEntities.size(); i++) {
            if (erpOrderEntities.get(i).getCommissionStatus() != CommissionStatusEnum.NOTENTERED.toInt()) {
                return R.error("请检查所选订单成本状态是否均为未录入状态!");
            }
        }
        map.put("commissionStatus", CommissionStatusEnum.Entered.toInt());
        this.baseMapper.batchAudit(map, idList);
        //添加订单日志
        List<ErpOrderLogEntity> orderLogEntityList = new ArrayList<>();
        for (int i = 0; i < idList.size(); i++) {
            String orderNo = idList.get(i);
            ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
            erpOrderLogEntity.setOrderNo(orderNo);
            erpOrderLogEntity.setCreateBy(createBy);
            erpOrderLogEntity.setCreateName(createName);
            erpOrderLogEntity.setCreateTime(new Date());
            erpOrderLogEntity.setLogText("erp批量录入");
            orderLogEntityList.add(erpOrderLogEntity);
        }
        if (orderLogEntityList.size() > 0) {
            erpOrderLogService.insertBatch(orderLogEntityList);
        }
        return R.ok();
    }

    /**
     * 自营门店分配
     *
     * @param price      商品单价
     * @param amount     商品总额
     * @param totalPrice 订单价格
     * @return
     */
    private List<OrderItemAllotResultVo> orderItemAllotToSelfMerchant(BigDecimal price, BigDecimal amount, BigDecimal totalPrice) {
        // 订单商品分配，默认查询所有自营门店进行分配
        List<OrderItemAllotResultVo> resultList = new ArrayList<>();
        List<Integer> sids = new ArrayList<>();
        sids.add(1);// 紫云网
        sids.add(18); // 阳逻工厂
        sids.add(20);// 配价工厂
        List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                .eq("seller_state", StateEnum.IS_AUDITED.toCode())
                .eq("self", 1)
                .notIn("seller_id", sids)
        );
        for (SellerInfoEntity sellerInfo : sellerInfoList) {
            OrderItemAllotResultVo resultVo = new OrderItemAllotResultVo();
            resultVo.setMerchantId(sellerInfo.getSellerId());
            resultVo.setMobile(sellerInfo.getSellerMobile());
            resultVo.setQq(sellerInfo.getSellerQq());
            resultVo.setMerchantName(sellerInfo.getSellerName());
            resultVo.setSelf(sellerInfo.getSelf().intValue() == 0 ? false : true);
            resultVo.setTotalPrice(totalPrice);
            resultVo.setAmount(amount);
            resultVo.setPrice(price);
            resultList.add(resultVo);
        }
        return resultList;
    }

    /**
     * 报价商品（快印、商务印刷）分配至自营门店，查询紫云网配价工厂的价格信息，作为所有自营门店的价格；
     * 分配至第三方，查询所有商户配价信息，需要去除自营门店信息。
     */
    @Override
    public R quoteOrderItemAllotFindFactory(Integer itemId, Integer sellerType) {
        log.info("================= quote item find factory api start==================");
        OrderItemEntity orderItem = orderItemService.selectById(itemId);
        MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
        multyErpOrderParam.setAllotOrderId(orderItem.getOrderId().toString());
        multyErpOrderParam.setGoodsSplitType(GoodsSplitType.quoteGoods);
        multyErpOrderParam.setOrderItemId(itemId);
        multyErpOrderParam.setOrderSplitType(OrderSplitType.ziyun_net);
        // 分配自营门店，referToSellerId 填写 紫云网配价工厂ID
        if (sellerType == 1) {
            multyErpOrderParam.setReferToSellerId(ErpOrderStateContext.ZIYUN_FACTORY_ID);
        }
        log.info("================= quote item find factory api param：" + JsonUtils.object2String(multyErpOrderParam));
        GoodsResult<?> goodsForOrderErp = goodsService.getGoodsForOrderErp(multyErpOrderParam);
        int code = goodsForOrderErp.getCode();
        if (code != 1) {
            String message = goodsForOrderErp.getMessage();
            if (code == 999) {
                log.info("================= quote item find factory api error：" + message);
                throw new RRException("派单服务异常，请联系后台管理员");
            }
            return R.error(message);
        }
        String data = JsonUtils.object2String(goodsForOrderErp.getData());
        QuoteResult quoteResult = JsonUtils.getJsonToObject(data, QuoteResult.class);
        List<FactoryQuoteInfo> factoryQuoteInfos = quoteResult.getFactoryQuoteInfos();
        if (factoryQuoteInfos.size() == 0) {
            return R.error("未查询到工厂信息");
        }
        if (sellerType == 1) {
            FactoryQuoteInfo factoryQuoteInfo = factoryQuoteInfos.get(0);
            Double totalPrice = factoryQuoteInfo.getTotalPrice();
            BigDecimal tprice = BigDecimal.valueOf(totalPrice).multiply(orderItem.getNums());
            List<OrderItemAllotResultVo> resultList = orderItemAllotToSelfMerchant(null, null, tprice);
            return R.ok().put("factoryInfosQuery", resultList);
        } else {
            List<FactoryQuoteInfo> collect = factoryQuoteInfos.stream().filter(item -> !item.getFactoryInfoVO().getSelf()).collect(Collectors.toList());
            for (FactoryQuoteInfo factoryQuoteInfo: collect){
                Double totalPrice = factoryQuoteInfo.getTotalPrice();
                BigDecimal tprice = BigDecimal.valueOf(totalPrice).multiply(orderItem.getNums());
                factoryQuoteInfo.setTotalPrice(tprice.doubleValue());
            }
            return R.ok().put("factoryQuoteInfos", collect);
        }
    }

    @Override
    public R orderCraftsInfo(Integer itemId) {
        OrderItemEntity orderItem = orderItemService.selectById(itemId);
        Long goodsId = orderItem.getGoodsId();
        String attributeOption = orderItem.getAttributeOption();
        if (StringUtils.isBlank(attributeOption)) {
            return R.error("缺少工序分配参数");
        }

        ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectByItemId(itemId);
        // 查询已分配工序列表
        List<OrderCraftQuoteDto> allotedList = erpOrderProductionService.selectAllotedCraftsList(itemId);
        // 查询分配服务工序信息、自做工序信息
        Integer eoItemId = erpOrderItem.getEoItemId();
        List<OrderCraftServerVo> serverList = erpOrderProductionService.selectAllotedServerCraftsList(eoItemId);
        // 查询自做外协信息（中浩紫云）
        ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineService.selectOne(new EntityWrapper<>(new ErpSupplierOfflineEntity())
                .eq("supplier_name", ErpOrderStateContext.ZIYUN_SUPP_NAME));
        Map<String, Map<AttributeValueType, Integer>> map = JSONObject.parseObject(attributeOption, Map.class);
        int size = map.size();
        List<QuoteAllotCraftsVo> craftsVoList = new ArrayList<>();
        Map<String, Object> queryMap = new HashMap<>();
        /**
         * 单部件：印刷、纸张，以及工艺进行分配
         * 多部件：主部件、子部件工艺参与分配，另外子部件印刷、纸张进行分配，拉页不显示分配列表，随内页工艺一起算价；
         */
        for (Map.Entry<String, Map<AttributeValueType, Integer>> entry : map.entrySet()) {
            String key = entry.getKey();
            Map<AttributeValueType, Integer> value = entry.getValue();
            boolean mainPart = false;
            // 部件名称：单部件查询分类名称；多部件查询部件名称；
            String partName = null;
            if (size > 1) {
                QuotePartsEntity quoteParts = quotePartsService.selectById(key);
                String pname = quoteParts.getPartsName();
                if (StringUtils.equals(pname, "拉页")) {
                    continue;
                }
                partName = pname;
                Integer isMainPart = quoteParts.getIsMainPart();
                if (isMainPart.intValue() == 1) {
                    mainPart = true;
                }
            } else {
                GoodsCategoryEntity goodsCategory = goodsCategoryService.selectById(key);
                partName = goodsCategory.getCategoryName();
            }

            if (!mainPart) {
                // 材料工艺
                QuoteAllotCraftsVo materialCrafts = new QuoteAllotCraftsVo();
                materialCrafts.setPartId(Integer.valueOf(key));
                materialCrafts.setPartsName(partName);
                materialCrafts.setAttributeName("纸张");
                materialCrafts.setCraftValueType(AttributeValueType.material.toString());
                materialCrafts.setSplitProcessType(SplitProcessType.material.toString());
                craftsVoList.add(materialCrafts);

                // 印刷工艺
                QuoteAllotCraftsVo sizeCrafts = new QuoteAllotCraftsVo();
                sizeCrafts.setPartId(Integer.valueOf(key));
                sizeCrafts.setPartsName(partName);
                sizeCrafts.setAttributeName("印刷");
                sizeCrafts.setCraftValueType(AttributeValueType.size.toString());
                sizeCrafts.setSplitProcessType(SplitProcessType.print.toString());
                craftsVoList.add(sizeCrafts);
            }

            Collection<Integer> values = value.values();
            List ids = new ArrayList(values);
            queryMap.put("mapSize", size);
            queryMap.put("goodsId", goodsId);
            queryMap.put("optionIds", ids);
            List<QuoteAllotCraftsVo> list = quoteProductBaseInfoService.getCraftsAllotInfo(queryMap);
            craftsVoList.addAll(list);

            // 回显已分配工序信息
            for (QuoteAllotCraftsVo craftsVo : craftsVoList) {
                List<OrderCraftQuoteDto> allotedListCollect = allotedList.stream()
                        .filter(item -> item.getPartId().intValue() == craftsVo.getPartId() && item.getCraftValueType().equals(craftsVo.getCraftValueType()))
                        .collect(Collectors.toList());
                if (allotedListCollect.size() > 0) {
                    OrderCraftQuoteDto orderCraftQuoteDto = allotedListCollect.get(0);
                    craftsVo.setFactoryName(orderCraftQuoteDto.getFactoryName());
                    craftsVo.setAddress(orderCraftQuoteDto.getAddress());
                    craftsVo.setContacts(orderCraftQuoteDto.getContacts());
                    craftsVo.setContactWay(orderCraftQuoteDto.getContactWay());
                    craftsVo.setTotalPrice(orderCraftQuoteDto.getTotalPrice());
                    craftsVo.setRemark(orderCraftQuoteDto.getRemark());
                    craftsVo.setAlloted(true);
                    craftsVo.setIsOwn(false);
                } else {
                    List<OrderCraftServerVo> serverListCollect = serverList.stream()
                            .filter(item -> item.getPartId().intValue() == craftsVo.getPartId() && item.getAttributeTypeValue().equals(craftsVo.getCraftValueType()))
                            .collect(Collectors.toList());
                    if (serverListCollect.size() > 0) {
                        OrderCraftServerVo orderCraftServerVo = serverListCollect.get(0);
                        craftsVo.setFactoryName(orderCraftServerVo.getSupplierName());
                        craftsVo.setAddress(orderCraftServerVo.getContactAddr());
                        craftsVo.setContacts(orderCraftServerVo.getContactsName());
                        craftsVo.setContactWay(orderCraftServerVo.getContactTel());
                        craftsVo.setTotalPrice(orderCraftServerVo.getTotalPrice());
                        craftsVo.setRemark(orderCraftServerVo.getRemark());
                        craftsVo.setAlloted(true);
                        craftsVo.setIsOwn(true);
                        serverList.removeAll(serverListCollect);
                    }
                }
            }
        }

        return R.ok().put("craftsList", craftsVoList)
                .put("serverCraftsList", serverList)
                .put("erpSupplierOffline", erpSupplierOffline);
    }

    @Override
    public R orderCraftAllotFindFactory(OrderCraftQuoteDto orderCraftQuoteDto) {
        log.info("================= craft item find factory api start==================");
        Integer orderItemId = orderCraftQuoteDto.getOrderItemId();
        String splitProcessType = orderCraftQuoteDto.getSplitProcessType();
        String craftValueType = orderCraftQuoteDto.getCraftValueType();
        Integer partId = orderCraftQuoteDto.getPartId();
        OrderItemEntity orderItem = orderItemService.selectById(orderItemId);
        Long orderId = orderItem.getOrderId();
        MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
        multyErpOrderParam.setAllotOrderId(orderId.toString());
        multyErpOrderParam.setGoodsSplitType(GoodsSplitType.quoteGoodsSplit);
        multyErpOrderParam.setOrderItemId(orderItemId);
        multyErpOrderParam.setPartId(partId);
        multyErpOrderParam.setSplitProcessType(com.service.common.constant.SplitProcessType.valueOf(splitProcessType));
        multyErpOrderParam.setCraftValueType(com.service.model.quote.constant.AttributeValueType.valueOf(craftValueType));
        multyErpOrderParam.setOrderSplitType(OrderSplitType.ziyun_net);
        log.info("================= craft find factory api param：" + JsonUtils.object2String(multyErpOrderParam));

        GoodsResult<?> goodsForOrderErp = goodsService.getGoodsForOrderErp(multyErpOrderParam);
        int code = goodsForOrderErp.getCode();
        if (code != 1) {
            String message = goodsForOrderErp.getMessage();
            if (code == 999) {
                log.info("================= craft find factory api error：" + message);
                throw new RRException("派单服务异常，请联系后台管理员");
            }
            return R.error(message);
        }
        String result = JsonUtils.object2String(goodsForOrderErp.getData());
        QuoteResult quoteResult = JsonUtils.getJsonToObject(result, QuoteResult.class);
        List<FactoryQuoteInfo> factoryQuoteInfos = quoteResult.getFactoryQuoteInfos();

        // 查询工厂列表是否包含 紫云配价工厂，若包含，显示所有自营门店可供分配
        Optional<FactoryQuoteInfo> factoryQuoteInfo = factoryQuoteInfos.stream()
                .filter(item -> item.getFactoryInfoVO().getId() == ErpOrderStateContext.ZIYUN_FACTORY_ID)
                .findFirst();
        if (factoryQuoteInfo.isPresent()) {
            FactoryQuoteInfo quoteInfo = factoryQuoteInfo.get();
            Double totalPrice = BigDecimal.valueOf(quoteInfo.getTotalPrice()).multiply(orderItem.getNums()).doubleValue();
            factoryQuoteInfos = factoryQuoteInfos.stream()
                    .filter(item -> item.getFactoryInfoVO().getId() != ErpOrderStateContext.ZIYUN_FACTORY_ID)
                    .collect(Collectors.toList());
            List<Integer> sids = new ArrayList<>();
            sids.add(1);// 紫云网
            sids.add(18); // 阳逻工厂
            sids.add(20);// 配价工厂
            List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                    .eq("seller_state", StateEnum.IS_AUDITED.toCode())
                    .eq("self", 1)
                    .notIn("seller_id", sids)
            );
            for (SellerInfoEntity sellerInfo : sellerInfoList) {
                FactoryInfoVO factoryInfoVO = new FactoryInfoVO();
                factoryInfoVO.setFactoryName(sellerInfo.getSellerName());
                factoryInfoVO.setContacts(sellerInfo.getName());
                factoryInfoVO.setContactWay(sellerInfo.getSellerMobile());
                factoryInfoVO.setAddress(sellerInfo.getAddr());
                factoryInfoVO.setQq(sellerInfo.getSellerQq());
                factoryInfoVO.setSelf(true);
                factoryInfoVO.setId(Long.valueOf(sellerInfo.getSellerId()));
                FactoryQuoteInfo info = new FactoryQuoteInfo();
                info.setFactoryInfoVO(factoryInfoVO);
                info.setTotalPrice(totalPrice);
                factoryQuoteInfos.add(info);
            }
        }
        return R.ok().put("factoryQuoteInfos", factoryQuoteInfos);
    }

    @Override
    public R orderTagChange(String orderNo, Integer orderTag) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("orderTag", orderTag);
        erpOrderService.updateByMap(updateMap, orderNo);
        return R.ok();
    }

    @Override
    public R orderAllotFindFactory(String orderNo) {
        List<OrderItemEntity> orderItemList = orderItemService.selectByOrderId(Long.valueOf(orderNo));
        List<String> goodsTypes = orderItemList.stream().map(OrderItemEntity::getGoodsType).collect(Collectors.toList());
        Set<String> setVal = new HashSet<>(goodsTypes);
        boolean fast = setVal.contains("fast"); // 快印
        boolean print = setVal.contains("print"); // 印刷
        boolean isAllot = false;
        boolean isStandard = true; // 是否标品
        // 1.商品类型都是快印或是印刷，进行报价商品分配 2.商品类型不是快印或印刷，进行标品商品分配
        if ((((fast && !print) || (!fast && print)) && setVal.size() == 1) || ((fast && print) && setVal.size() == 2)) {
            isAllot = true;
            isStandard = false;
        } else if (!fast && !print) {
            isAllot = true;
        }
        if (!isAllot) {
            return R.error("订单商品类型不允许分配");
        }

        if (isStandard) {
            // 标品 找寻自营门店
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (OrderItemEntity itemEntity : orderItemList) {
                Integer productId = itemEntity.getProductId();
                String name = itemEntity.getName();
                // 标品，查询门店配置价格信息(价格以紫云网配置价格为准)
                List<StoreGoodsProductEntity> storeGoodsProductList = storeGoodsProductService.selectList(new EntityWrapper<>(new StoreGoodsProductEntity())
                        .eq("orig_product_id", productId)
                        .eq("disabled", DeleteEnum.NOT_DELETE.toInt())
                );
                if (storeGoodsProductList.size() == 0) {
                    return R.error("未查询到自营门店上架商品：" + name);
                }
                List<Integer> productIds = storeGoodsProductList.stream().map(StoreGoodsProductEntity::getProductId).collect(Collectors.toList());
                Map<String, Object> params = new HashMap<>();
                params.put("productIds", productIds);
                List<StoreProductPriceVo> storeProductPriceVos = storeProductPriceService.selectStoreProductPriceVoList(params);
                // 查询 紫云工厂(分配) 账号是否配价格，若配价格，以此价格为准；若未配价格，提示返回
                List<StoreProductPriceVo> storeProductPriceVoList = storeProductPriceVos.stream()
                        .filter((item) -> item.getSellerId().intValue() == ErpOrderStateContext.ZIYUN_FACTORY_ID.intValue())
                        .collect(Collectors.toList());
                if (storeProductPriceVoList.size() == 0) {
                    return R.error("商品未配置价格");
                }
                StoreProductPriceVo storeProductPrice = storeProductPriceVoList.get(0);
                BigDecimal price = storeProductPrice.getPrice();
                BigDecimal nums = itemEntity.getNums();
                // 查询是否有阶梯价
                String stepPrice = storeProductPrice.getStepPrice();
                if (StringUtils.isNotBlank(stepPrice)) {
                    BigDecimal sprice = calculateStepPrice(stepPrice, nums);
                    if (sprice != null) {
                        price = sprice;
                    }
                }
                BigDecimal amount = price.multiply(nums);

                // 查询是否广告物料商品
                String goodsType = itemEntity.getGoodsType();
                if (goodsType.equals(GoodsTypeEnum.MATERIAL.toCode())) {
                    Long goodsId = itemEntity.getGoodsId();
                    String addon = itemEntity.getAddon();
                    BigDecimal aprice = calculateMaterialGoodsPrice(goodsId, addon, amount);
                    if (aprice != null) {
                        amount = aprice;
                    }
                }
                totalPrice = totalPrice.add(amount);
            }
            List<OrderItemAllotResultVo> storeInfosQuery = orderItemAllotToSelfMerchant(null, null, totalPrice);
            return R.ok().put("storeInfosQuery", storeInfosQuery).put("isStandard", isStandard);
        } else {
            log.info("================= quote item find factory api start==================");
            // 报价商品 找寻分配工厂
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (OrderItemEntity itemEntity : orderItemList) {
                Integer itemId = itemEntity.getItemId();
                MultyErpOrderParam multyErpOrderParam = new MultyErpOrderParam();
                multyErpOrderParam.setAllotOrderId(orderNo);
                multyErpOrderParam.setGoodsSplitType(GoodsSplitType.quoteGoods);
                multyErpOrderParam.setOrderItemId(itemId);
                multyErpOrderParam.setOrderSplitType(OrderSplitType.ziyun_net);
                multyErpOrderParam.setReferToSellerId(ErpOrderStateContext.ZIYUN_FACTORY_ID);
                log.info("================= quote item find factory api param：" + JsonUtils.object2String(multyErpOrderParam));
                GoodsResult<?> goodsForOrderErp = goodsService.getGoodsForOrderErp(multyErpOrderParam);
                int code = goodsForOrderErp.getCode();
                if (code != 1) {
                    String message = goodsForOrderErp.getMessage();
                    if (code == 999) {
                        log.info("================= quote item find factory api error：" + message);
                        throw new RRException("派单服务异常，请联系后台管理员");
                    }
                    return R.error(message);
                }
                String data = JsonUtils.object2String(goodsForOrderErp.getData());
                QuoteResult quoteResult = JsonUtils.getJsonToObject(data, QuoteResult.class);
                // 符合报价产品的条件的工厂详情
                List<FactoryQuoteInfo> factoryQuoteInfos = quoteResult.getFactoryQuoteInfos();
                if (factoryQuoteInfos.size() == 0) {
                    return R.error("商品：" + itemEntity.getName() + "未找到工厂信息");
                }
                FactoryQuoteInfo factoryQuoteInfo = factoryQuoteInfos.get(0);
                totalPrice = totalPrice.add(BigDecimal.valueOf(factoryQuoteInfo.getTotalPrice()).multiply(itemEntity.getNums()));
            }
            // 报价商品订单分配，默认查询所有自营门店进行分配
            List<Integer> sids = new ArrayList<>();
            sids.add(1);// 紫云网
            sids.add(18); // 阳逻工厂
            sids.add(20);// 配价工厂
            List<SellerInfoEntity> sellerInfoList = sellerInfoService.selectList(new EntityWrapper<>(new SellerInfoEntity())
                    .eq("seller_state", StateEnum.IS_AUDITED.toCode())
                    .eq("self", 1)
                    .notIn("seller_id", sids)
            );
            return R.ok().put("sellerInfoList", sellerInfoList)
                    .put("totalPrice", totalPrice)
                    .put("isStandard", isStandard);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderReceiverUpdate(ErpOrderEntity erpOrder) {
        String orderNo = erpOrder.getOrderNo();
        String shipName = erpOrder.getShipName();
        String shipMobile = erpOrder.getShipMobile();
        String shipAddr = erpOrder.getShipAddr();
        String shipZip = erpOrder.getShipZip();
        Integer sendType = erpOrder.getSendType();
        Integer shipAreaId = erpOrder.getShipAreaId();
        String shipArea = erpOrder.getShipArea();
        BigDecimal costFreight = erpOrder.getCostFreight();
        BigDecimal payableAmountNow = null;
        ErpOrderEntity erpOrderEntity = this.selectById(orderNo);
        Map<String, Object> updateMap = new HashMap<>();
        if (erpOrderEntity == null) {
            OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderNo);
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            BigDecimal costFreightOri = orderInfoEntity.getCostFreight();
            int compare = costFreightOri.compareTo(costFreight);
            if (compare != 0) {
                String payStatus = orderInfoEntity.getPayStatus();
                if (payStatus.equals(PayStatusEnum.ALREADY_PAY_1.toCode())) {
                    return R.error("订单已支付，无法修改配送价格");
                }
                BigDecimal payableAmount = orderInfoEntity.getPayableAmount();
                payableAmountNow = payableAmount.subtract(costFreightOri).add(costFreight);
                erpOrderEntity.setPayableAmount(payableAmountNow);
            }
            erpOrderEntity.setCostFreight(costFreight);
            erpOrderEntity.setShipName(shipName);
            erpOrderEntity.setShipMobile(shipMobile);
            erpOrderEntity.setShipAddr(shipAddr);
            erpOrderEntity.setShipZip(shipZip);
            erpOrderEntity.setSendType(sendType);
            erpOrderEntity.setShipAreaId(shipAreaId);
            erpOrderEntity.setShipArea(shipArea);
            this.insert(erpOrderEntity);
            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderNo));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderNo);
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        } else {
            BigDecimal costFreightOri = erpOrderEntity.getCostFreight();
            int compare = costFreightOri.compareTo(costFreight);
            if (compare != 0) {
                Integer payStatus = erpOrderEntity.getPayStatus();
                if (payStatus.intValue() == Integer.valueOf(PayStatusEnum.ALREADY_PAY_1.toCode())) {
                    return R.error("订单已支付，无法修改配送价格");
                }
                BigDecimal payableAmount = erpOrderEntity.getPayableAmount();
                payableAmountNow = payableAmount.subtract(costFreightOri).add(costFreight);
                updateMap.put("payableAmount", payableAmountNow);
            }
            updateMap.put("costFreight", costFreight);
            updateMap.put("shipName", shipName);
            updateMap.put("shipMobile", shipMobile);
            updateMap.put("shipAddr", shipAddr);
            updateMap.put("shipZip", shipZip);
            updateMap.put("sendType", sendType);
            updateMap.put("shipAreaId", shipAreaId);
            updateMap.put("shipArea", shipArea);
            this.updateByMap(updateMap, orderNo);
        }

        // 更新订单信息
        updateMap.clear();
        updateMap.put("costFreight", costFreight);
        updateMap.put("shipName", shipName);
        updateMap.put("shipMobile", shipMobile);
        updateMap.put("shipAddr", shipAddr);
        updateMap.put("shipZip", shipZip);
        updateMap.put("sendType", sendType);
        updateMap.put("shipAreaId", shipAreaId);
        updateMap.put("shipArea", shipArea);
        updateMap.put("pickUp", sendType);
        if (payableAmountNow != null) {
            updateMap.put("payableAmount", payableAmountNow);
        }
        orderInfoService.updateByMap(updateMap, orderNo);

        // 订单日志
        erpOrderLogService.insertOrderLog(erpOrderEntity.getOrderNo(), "修改收货人信息");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R suppSave(OrderSupplierDto orderSupplierDto, Long userId) {
        Integer eoItemId = orderSupplierDto.getEoItemId();
        ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectById(eoItemId);

        // 若商品分配工厂或添加服务工序，不允许添加外协
        List<ErpOrderProductionEntity> productionEntityList = erpOrderProductionService.selectList(new EntityWrapper<>(new ErpOrderProductionEntity())
                .eq("erp_item_id", eoItemId)
                .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
        );
        long count = productionEntityList.stream().filter(item -> item.getProducerType().intValue() != ProducerTypeEnum.ZIYUN_SUPPLIER.toInt()).count();
        if (count == 0) {
            count = productionEntityList.stream().filter(item -> item.getAllotType().equals(AllotTypeEnum.PROCEDURE.toCode())).count();
        }
        if (count > 0) {
            return R.error("商品已分配工厂，无法添加外协商");
        }

        // 若商品是设计商品分配（商品生产完成，但没有生产单信息），无法添加外协商
        int size = productionEntityList.size();
        Integer status = erpOrderItem.getStatus();
        if (size == 0 && status.intValue() == OrderItemStatusEnum.PRODUCTION_FINISH.toInt()) {
            return R.error("商品已进行设计商品分配，无法添加外协商");
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderItemStatusEnum.IN_PRODUCTION.toInt());
        erpOrderItemService.updateByMap(updateMap, erpOrderItem.getEoItemId());

        ErpOrderEntity erpOrder = this.selectById(orderSupplierDto.getOrderId());
        Integer productionStatus = erpOrder.getProductionStatus();
        if (productionStatus.intValue() == ProductionStatusEnum.UN_ALLOT.toInt()) {
            updateMap.clear();
            updateMap.put("csId", orderSupplierDto.getCsId());
            updateMap.put("pmcId", orderSupplierDto.getPmcId());
            updateMap.put("allotName", userId);
            updateMap.put("allotTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
            this.updateByMap(updateMap, orderSupplierDto.getOrderId());
        }

        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderSupplierDto.getOrderId());
        erpOrderProduction.setErpItemId(eoItemId.toString());
        erpOrderProduction.setOrderItemId(orderSupplierDto.getOriginalItemId().toString());
        erpOrderProduction.setAttributeName(orderSupplierDto.getAttributeName());
        BigDecimal cost = orderSupplierDto.getCost();
        if (cost != null) {
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(orderSupplierDto.getSupplierId());
        ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineService.selectById(orderSupplierDto.getSupplierId());
        erpOrderProduction.setProducerName(erpSupplierOffline.getSupplierName());
        erpOrderProduction.setCsRemark(orderSupplierDto.getCsRemark());
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.PRODUCING.toInt());
        erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
        erpOrderProduction.setCreateName(userId.toString());
        erpOrderProduction.setAllotType(AllotTypeEnum.GOODS.toCode());
        erpOrderProductionService.insert(erpOrderProduction);

        erpOrderLogService.insertOrderItemLog(orderSupplierDto.getOrderId(), Long.valueOf(orderSupplierDto.getOriginalItemId()), "添加外协商");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R costSave(OrderSupplierDto orderSupplierDto, Long userId) {
        Integer eoItemId = orderSupplierDto.getEoItemId();
        ErpOrderProductionEntity erpOrderProduction = new ErpOrderProductionEntity();
        erpOrderProduction.setOrderNo(orderSupplierDto.getOrderId());
        erpOrderProduction.setErpItemId(eoItemId.toString());
        erpOrderProduction.setOrderItemId(orderSupplierDto.getOriginalItemId().toString());
        erpOrderProduction.setAttributeName(orderSupplierDto.getAttributeName());
        BigDecimal cost = orderSupplierDto.getCost();
        if (cost != null) {
            erpOrderProduction.setCostStatus(true);
            erpOrderProduction.setCost(cost);
        }
        erpOrderProduction.setProducer(orderSupplierDto.getSupplierId());
        ErpSupplierOfflineEntity erpSupplierOffline = erpSupplierOfflineService.selectById(orderSupplierDto.getSupplierId());
        erpOrderProduction.setProducerName(erpSupplierOffline.getSupplierName());
        erpOrderProduction.setCsRemark(orderSupplierDto.getCsRemark());
        erpOrderProduction.setProductionStatus(OrderProductionStatusEnum.FINISH.toInt());
        erpOrderProduction.setProducerType(ProducerTypeEnum.ZIYUN_SUPPLIER.toInt());
        erpOrderProduction.setCreateName(userId.toString());
        erpOrderProduction.setAllotType(AllotTypeEnum.GOODS.toCode());
        erpOrderProductionService.insert(erpOrderProduction);

        erpOrderLogService.insertOrderItemLog(orderSupplierDto.getOrderId(), Long.valueOf(orderSupplierDto.getOriginalItemId()), "外协成本录入");

        return R.ok();
    }

    @Override
    public OrderResult<AllotOrderResultDto> orderAllotApi(ErpAllotFactoryOrderParamDto erpAllotFactoryOrderParamDto) {
        OrderResult<AllotOrderResultDto> allotOrderResultDtoOrderResult = mallErpOrderService.allotFactoryOrder(erpAllotFactoryOrderParamDto);
        return allotOrderResultDtoOrderResult;
    }

    /**
     * 订单自动确认收货
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R doOrderFinishJob() {
//        List<OrderInfoEntity>  orderInfoEntityList = baseMapper.selectdoOrderFinishList();
//
//        // 已完成订单号
//        List<String> orderIds = new ArrayList<>();
//        for (OrderInfoEntity orderInfoEntity:orderInfoEntityList){
//            orderIds.add(orderInfoEntity.getOrderId());
//        }
//        if(orderIds.size() > 0){
//            orderInfoService.updateFinishStatus(orderIds);
//            baseMapper.updateFinishStatus(orderIds);
//        }
//
//        return R.ok("确认收货完成：操作订单数："+ orderInfoEntityList.size());
        return R.ok();
    }

    @Override
    public List<ErpCustomerServieceUserEntity> getCsOrPmcList(int type) {
        return this.baseMapper.getCsOrPmcList(type);
    }

    /**
     * 设计商品审核:只改变商品、订单状态，不生成生产单信息
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R allotOrderItemDesign(OrderItemAllotDto orderItemAllotDto) {
        Integer erpItemId = orderItemAllotDto.getErpItemId();
        ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectById(erpItemId);
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
        erpOrderItemService.updateByMap(updateMap, erpOrderItem.getEoItemId());
        String orderNo = erpOrderItem.getOrderNo();
        ErpOrderEntity erpOrder = this.selectById(orderNo);
        Integer productionStatus = erpOrder.getProductionStatus();
        List<Integer> status = new ArrayList<>();
        status.add(OrderItemStatusEnum.PRODUCTION_FINISH.toInt());
        status.add(OrderItemStatusEnum.DELIVERED.toInt());
        int selectCount = erpOrderItemService.selectCount(new EntityWrapper<>(new ErpOrderItemEntity())
                .eq("order_no", orderNo)
                .notIn("status", status)
                .eq("item_del", DeleteEnum.NOT_DELETE.toInt())
        );

        updateMap.clear();
        if (productionStatus.intValue() == ProductionStatusEnum.UN_ALLOT.toInt()){
            updateMap.put("csId", orderItemAllotDto.getCsId());
            updateMap.put("pmcId", orderItemAllotDto.getPmcId());
            updateMap.put("allotName", orderItemAllotDto.getUserId());
            updateMap.put("allotTime", io.renren.common.utils.DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }
        if (selectCount == 0) {
            updateMap.put("productionStatus", ProductionStatusEnum.PRODUCTION_FINISH.toInt());
            updateMap.put("finishTime", io.renren.common.utils.DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }else {
            updateMap.put("productionStatus", ProductionStatusEnum.IN_PRODUCTION.toInt());
        }
        this.updateByMap(updateMap, orderNo);

        erpOrderLogService.insertOrderItemLog(orderNo, Long.valueOf(erpOrderItem.getOriginalItemId()), "分配中心-设计商品分配");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderInit(String orderId, Long userId) {
        OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderId);
        try {
            Date date = DateUtils.parseDateTime("2018-11-01 21:10:00");
            if (orderInfoEntity.getCreatetime().after(date)) {
                return R.error("只允许初始化旧系统（2018-11-01 21:10:00之前）的订单");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 旧版系统的分配信息存在表 erp_order_allot_relevance 中
        // 订单如果分配的是工厂，暂且无法初始化，需提示出来，人工进行判断处理
        List<OriginalRelevanceVo> relevanceList = erpOrderAllotRelevanceService.selectInfoByOriginalOrderNo(orderId);
        if (relevanceList.size() > 0) {
            return R.error().put("relevanceList", relevanceList);
        }

        Map<String, Object> updateMap = new HashMap<>();
        // 取消生产单信息
        updateMap.put("productionStatus", OrderProductionStatusEnum.CANCLE.toInt());
        erpOrderProductionService.updateByMapOrderId(updateMap, orderId);

        // 商品状态置为 待分配
        updateMap.clear();
        updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
        erpOrderItemService.updateByMapOrderId(updateMap, orderId);

        // 订单状态置为 待分配
        updateMap.clear();
        updateMap.put("productionStatus", ProductionStatusEnum.UN_ALLOT.toInt());
        this.updateByMap(updateMap, orderId);

        erpOrderLogService.insertOrderLog(orderId, "订单初始化");

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synProduce(Integer sellerId, Integer type) {
        String datetime = "2018-01-01 00:00:00";
        if (type == 1) {
            datetime = "2018-12-08 00:00:00";
        }
        List<OrderInfoEntity> orderInfoEntityList = orderInfoService.selectNotProductOrderList(sellerId, datetime);
        log.info("========== 转移订单数量：" + orderInfoEntityList.size() + " 条 ========== ");
        List<ErpOrderEntity> erpOrderEntityList = new ArrayList<>();
        List<ErpOrderItemEntity> erpOrderItemEntityList = new ArrayList<>();
        for (OrderInfoEntity orderInfoEntity : orderInfoEntityList) {
            log.info("========== 循环订单 支付状态：" + orderInfoEntity.getPayStatus() + "  ========== ");
            if (!"1".equals(orderInfoEntity.getPayStatus())) {
                // 并且不是分配单，则跳过
                int count = erpOrderAllotRelevanceService.selectCount(new EntityWrapper<ErpOrderAllotRelevanceEntity>()
                        .eq("order_allot_no", orderInfoEntity.getOrderId()).eq("del", DeleteEnum.NOT_DELETE.toInt()));
                if (count == 0) {
                    continue;
                }
            }
            ErpOrderEntity erpOrder = erpOrderService.selectByNo(orderInfoEntity.getOrderId());

            if (erpOrder != null) {
                continue;
            }
            ErpOrderEntity erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrderEntityList.add(erpOrderEntity);
//            erpOrderService.insert(erpOrderEntity);
            List<OrderItemEntity> orderItemEntities = orderItemService.selectByOrderId(Long.valueOf(orderInfoEntity.getOrderId()));

            List<ErpOrderItemEntity> erpOrderItemEntities = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntities, orderInfoEntity.getOrderId());
//            erpOrderItemService.saveBatch(erpOrderItemEntities);
            erpOrderItemEntityList.addAll(erpOrderItemEntities);
        }

        if (erpOrderEntityList.size() > 0) {
            erpOrderService.insertBatch(erpOrderEntityList);
            log.info("========== 插入主表：" + erpOrderEntityList.size() + "  ========== ");
        }
        if (erpOrderItemEntityList.size() > 0) {
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
            log.info("========== 插入明细：" + erpOrderItemEntityList.size() + "  ========== ");

        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synErpOrderToOrderInfo(Integer sellerId) {
        List<ErpOrderEntity> erpOrderEntityList = erpOrderService.selectList(
                new EntityWrapper<ErpOrderEntity>().eq("order_source", OrderSourceEnum.OFFlINE.toInt())
                        .eq("third_merchant_id", sellerId).ge("order_createtime", "2018-11-01 00:00:00"));
        log.info("========== 转移订单数量：" + erpOrderEntityList.size() + " 条 ========== ");
        List<OrderInfoEntity> addOrderInfoEntityList = new ArrayList<>();
        List<OrderInfoEntity> updateOrderInfoEntityList = new ArrayList<>();
        List<ErpOrderItemEntity> addErpOrderItemEntity = new ArrayList<>();
        List<OrderItemEntity> updateOrderItemEntity = new ArrayList<>();
        for (ErpOrderEntity erpOrderEntity : erpOrderEntityList) {
            OrderInfoEntity orderInfo = orderInfoService.selectById(erpOrderEntity.getOrderNo());
            OrderInfoEntity orderInfoEntity = ErpOrderUtils.erpToZiyunOrder(erpOrderEntity);
            if (orderInfo != null) {
                //如果已经存在，则需要更改状态
                updateOrderInfoEntityList.add(orderInfoEntity);
            } else {
                addOrderInfoEntityList.add(orderInfoEntity);
            }
            //再根据订单号查询商品
            List<ErpOrderItemEntity> erpOrderItemEntities = erpOrderItemService.selectList(
                    new EntityWrapper<ErpOrderItemEntity>().eq("order_no", erpOrderEntity.getOrderNo()));
            //如果商品已经存在关联original_item_id。则添加到修改集合中，否则添加到新增集合中
            for (int i = 0; i < erpOrderItemEntities.size(); i++) {
                ErpOrderItemEntity erpOrderItemEntity = erpOrderItemEntities.get(i);
                if (erpOrderItemEntity.getOriginalItemId() != null) {
                    updateOrderItemEntity.add(ErpOrderUtils.erpToZiyunOrderItem(erpOrderItemEntity));
                } else {
                    addErpOrderItemEntity.add(erpOrderItemEntity);
                }
            }
        }
        //如果是修改，则直接修改即可
        if (updateOrderItemEntity.size() > 0) {
            orderItemService.updateBatchById(updateOrderItemEntity);
        }
        if (addErpOrderItemEntity.size() > 0) {
            List<ErpOrderItemEntity> erpOrderItemEntities = new ArrayList<>();
            for (int i = 0; i < addErpOrderItemEntity.size(); i++) {
                ErpOrderItemEntity erpOrderItemEntity = addErpOrderItemEntity.get(i);
                OrderItemEntity orderItemEntity = ErpOrderUtils.erpToZiyunOrderItem(erpOrderItemEntity);
                boolean b = orderItemService.insert(orderItemEntity);
                if (b) {
                    erpOrderItemEntity.setOriginalItemId(orderItemEntity.getItemId());
                    erpOrderItemEntities.add(erpOrderItemEntity);
                }
            }
            erpOrderItemService.updateBatchById(erpOrderItemEntities);
        }
        if (updateOrderInfoEntityList.size() > 0) {
            orderInfoService.updateBatchById(updateOrderInfoEntityList);
        }
        if (addOrderInfoEntityList.size() > 0) {
            orderInfoService.insertBatch(addOrderInfoEntityList);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sellerOrderReward(OrderBonusVo orderBonusVo, int multiple) {
        String orderId = orderBonusVo.getOrderId();
        UserPaymentEntity userPayment = userPaymentService.getPaySuccLastEntityByOrderId(orderId);
        if (userPayment == null) {
            throw new RRException("订单支付信息异常");
        }

        Integer supplierId = orderBonusVo.getSupplierId();
        Integer mallUserId = sellerInfoService.selectPopSellerInfo(supplierId);
        if (mallUserId == null) {
            throw new RRException("未找到商户会员信息");
        }
        UserWalletEntity userWallet = userWalletService.selectById(mallUserId);
        if (userWallet == null) {
            throw new RRException("未找到商户钱包信息");
        }

        BigDecimal scholarship = userWallet.getScholarship();
        Integer bonusType = orderBonusVo.getBonusType();
        Map<String, Object> updateMap = new HashMap<>();
        if (bonusType.intValue() == 0) {
            BigDecimal pmtRandom = orderBonusVo.getPmtRandom();
            int compare = pmtRandom.compareTo(BigDecimal.ZERO);
            if (compare > 0) {
                // 乘以奖励金倍数
                pmtRandom = pmtRandom.multiply(BigDecimal.valueOf(multiple));
                scholarship = scholarship.add(pmtRandom);
                updateMap.put("scholarship", scholarship);
                userWalletService.updateByMap(updateMap, mallUserId);

                String paymentId = userPayment.getPaymentId();
                Date tPayed = userPayment.getTPayed();
                UserScholarshipEntity userScholarship = new UserScholarshipEntity();
                userScholarship.setPaymentId(paymentId);
                userScholarship.setMtime(tPayed);
                userScholarship.setOrderId(Long.valueOf(orderId));
                userScholarship.setUserId(mallUserId);
                userScholarship.setMoney(pmtRandom);
                userScholarship.setMessage("奖励金结算");
                userScholarship.setImportMoney(pmtRandom);
                userScholarshipService.insert(userScholarship);
            }

        } else {
            BigDecimal bonusAmount = orderBonusVo.getBonusAmount();
            int compare = bonusAmount.compareTo(BigDecimal.ZERO);
            if (compare > 0) {
                scholarship = scholarship.add(bonusAmount);
                updateMap.put("scholarship", scholarship);
                userWalletService.updateByMap(updateMap, mallUserId);

                String paymentId = userPayment.getPaymentId();
                Date tPayed = userPayment.getTPayed();
                UserScholarshipEntity userScholarship = new UserScholarshipEntity();
                userScholarship.setPaymentId(paymentId);
                userScholarship.setMtime(tPayed);
                userScholarship.setOrderId(Long.valueOf(orderId));
                userScholarship.setUserId(mallUserId);
                userScholarship.setMoney(bonusAmount);
                userScholarship.setMessage("奖励金结算");
                userScholarship.setImportMoney(bonusAmount);
                userScholarshipService.insert(userScholarship);
            }
        }

        ErpOrderEntity erpOrderEntity = this.selectById(orderId);
        if (erpOrderEntity == null) {
            OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderId);
            erpOrderEntity = ErpOrderUtils.ziyunOrderToErp(orderInfoEntity);
            erpOrderEntity.setRewardStatus(1);
            this.insert(erpOrderEntity);
            List<OrderItemEntity> orderItemEntityList = orderItemService.selectByOrderId(Long.valueOf(orderId));
            List<ErpOrderItemEntity> erpOrderItemEntityList = ErpOrderUtils.ziyunOrderItemToErp(orderItemEntityList, orderId);
            erpOrderItemService.insertBatch(erpOrderItemEntityList);
        } else {
            updateMap.clear();
            updateMap.put("rewardStatus", 1);
            this.updateByMap(updateMap, orderId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R sellerOrderPay(SellerOrderPayDto sellerOrderPayDto) {
        String orderId = sellerOrderPayDto.getOrderId();
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("graphicShopPayStatus", 1);
        updateMap.put("graphicShopPayDate", DateUtils.format(sellerOrderPayDto.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
        updateMap.put("graphicShopPayRemarks", sellerOrderPayDto.getRemark());
        this.baseMapper.updateByMap(updateMap, orderId);

        // 是否存在分配信息（即分配的工厂订单），需要生产单更新打款状态
        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.selectOne(new EntityWrapper<>(new ErpOrderProductionEntity()).eq("production_order", orderId));
        if (erpOrderProduction != null) {
            Integer productionId = erpOrderProduction.getProductionId();
            updateMap.clear();
            updateMap.put("financeStatus", 3);
            updateMap.put("financePaytime", DateUtils.format(sellerOrderPayDto.getPayTime(), "yyyy-MM-dd HH:mm:ss"));
            updateMap.put("financeRemark", sellerOrderPayDto.getRemark());
            erpOrderProductionService.updateByMap(updateMap, productionId);
        }

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sellerCashBack(List<String> allotOrderList) {
        for (String allotOrder : allotOrderList) {
            // 修改生产单 财务提现信息
            List<ErpOrderProductionEntity> erpOrderProductionEntityList = erpOrderProductionService.selectList(
                    new EntityWrapper<ErpOrderProductionEntity>()
                            .eq("del", 0)
                            .eq("online_cash", 1)
                            .eq("production_order", allotOrder)
            );
            if (erpOrderProductionEntityList == null || erpOrderProductionEntityList.size() != 1) {
                continue;
            }
            ErpOrderProductionEntity erpOrderProductionEntity = erpOrderProductionEntityList.get(0);

            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("financeStatus", 3);
            updateMap.put("financePaytime", io.renren.common.utils.DateUtils.format(new Date()));
            updateMap.put("financeRemark", "商户提现，系统自动付款");
            updateMap.put("updateName", "admin");
            erpOrderProductionService.updateByMap(updateMap, erpOrderProductionEntity.getProductionId());

            ErpOrderEntity erpOrderEntity = erpOrderService.selectByNo(allotOrder);
            if (erpOrderEntity == null) {
                continue;
            }
            updateMap.clear();
            updateMap.put("graphicShopPaystatus", 1);
            updateMap.put("graphicShopPayDate", io.renren.common.utils.DateUtils.format(new Date()));
            updateMap.put("graphicShopPayRemarks", "商户提现，系统自动付款");
            erpOrderService.updateByMap(updateMap, erpOrderEntity.getOrderNo());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R resetOrderItemDesign(Integer eoItemId) {
        ErpOrderItemEntity erpOrderItem = erpOrderItemService.selectById(eoItemId);
        Integer status = erpOrderItem.getStatus();
        if (status.intValue() != OrderItemStatusEnum.PRODUCTION_FINISH.toInt()) {
            return R.error("商品状态异常");
        }

        Integer originalItemId = erpOrderItem.getOriginalItemId();
        int selectCount = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                .eq("order_item_id", originalItemId)
                .eq("del", DeleteEnum.NOT_DELETE.toInt())
                .ne("production_status", OrderProductionStatusEnum.CANCLE.toInt())
        );
        if (selectCount > 0) {
            return R.error("商品分配信息异常");
        }

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
        erpOrderItemService.updateByMap(updateMap, eoItemId);

        // 查询订单是否已发货，若已发货，取消分配不影响订单状态
        String orderNo = erpOrderItem.getOrderNo();
        ErpOrderEntity erpOrderEntity = this.selectById(orderNo);
        Integer shipStatus = erpOrderEntity.getShipStatus();
        if (shipStatus.intValue() == 0) {
            // 订单下所有商品是否取消分配
            int count = erpOrderItemService.selectCount(new EntityWrapper<>(new ErpOrderItemEntity())
                    .eq("order_no", orderNo)
                    .eq("item_del", DeleteEnum.NOT_DELETE.toInt())
                    .ne("status", OrderItemStatusEnum.UN_ALLOTED.toInt())
            );
            if (count == 0) {
                erpOrderService.cancelOrderAllotInfo(orderNo);
            }
        }

        erpOrderLogService.insertOrderItemLog(orderNo, Long.valueOf(erpOrderItem.getOriginalItemId()), "设计商品取消分配");

        return R.ok();
    }

    /**
     * 紫云网提成核算 OrderRoyaltyController
     *
     * @param params 列表
     * @return
     */
    public R queryOrderRoyaltyPage(Map<String, Object> params) {
        Page<OrderRoyaltyVo> page = new Page<>(Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("limit").toString()));
        page.setRecords(this.baseMapper.queryOrderRoyaltyPage(page, params));
        PageUtils pageUtils = new PageUtils(page);
        // 合计-金额map
        Map<String, Object> totalSum = this.baseMapper.sumOrderCost(params);
        //枚举
        Map<String, Object> mapEnum = new HashMap<>();
        mapEnum.put("productionStatusEnum", JsonUtils.enumToList(ProductionStatusEnum.class));
        mapEnum.put("commissionStatusEnum", JsonUtils.enumToList(CommissionStatusEnum.class));
        mapEnum.put("totalSum", totalSum);
        return R.ok().put("page", pageUtils).put("userData", mapEnum);
    }

    /**
     * 订单信息
     *
     * @param orderNo
     * @return
     */
    public R orderRoyaltyInfoById(String orderNo) {
        R re = R.ok();
        //订单信息
        ErpOrderEntity erpOrder = erpOrderService.selectById(orderNo);
        re.put("erpOrder", erpOrder);
        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.selectList(
                new EntityWrapper<ErpOrderItemEntity>()
                        .eq("order_no", orderNo)
                        .eq("item_del", 0)
        );

        re.put("orderItemDetailData", orderItemDetailData);
        //查询物流列表
        List<OrderLogisticsEntity> orderLogisticsList = orderLogisticsService.selectByOrderNo(orderNo);
        re.put("orderLogisticsList", orderLogisticsList);
        return re;
    }

    /**
     * 批量录入
     *
     * @param orderNos
     * @return
     */
    public R batchInput(String orderNos) {
        String[] split = orderNos.split(",");
        List<String> list = Arrays.asList(split);
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            ids.add(split[i]);
        }
        List<ErpOrderEntity> orderEntityList = this.selectBatchIds(list);
        //判断订单是否已完成
        for (int i = 0; i < orderEntityList.size(); i++) {
            if (orderEntityList.get(i).getProductionStatus() != ProductionStatusEnum.FINISH.toInt()) {
                return R.error("请检查订单是否是  已完成  状态");
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("commissionStatus", CommissionStatusEnum.Entered.toInt());
        baseMapper.batchAudit(map, ids);
        for (ErpOrderEntity erpOrder : orderEntityList) {
            String orderNo = erpOrder.getOrderNo();
            String createName = UserUtil.getCurrentUser().getUsername();
            Date createTime = new Date();
            erpOrderLogService.insertOrderLog(orderNo, "erp订单修改提成核算状态" + ' ' + createName + ' ' + createTime);
        }
        return R.ok();

    }

    public R audit(String orderNo) {
        Map<String, Object> map = new HashMap<>();
        map.put("commissionStatus", CommissionStatusEnum.SETTLED.toInt());
        baseMapper.updateByMap(map, orderNo);
        //写入日志
        String createName = UserUtil.getCurrentUser().getUsername();
        Date createTime = new Date();
        erpOrderLogService.insertOrderLog(orderNo, "erp订单修改提成核算状态" + ' ' + createName + ' ' + createTime);
        return R.ok();

    }

    /**
     * 撤销审核
     *
     * @param orderNo
     * @return
     */
    public R Revoke(String orderNo) {
        Map<String, Object> map = new HashMap<>();
        ErpOrderEntity erpOrderEntity = this.selectByNo(orderNo);
        if (erpOrderEntity.getCommissionStatus() == CommissionStatusEnum.SETTLED.toInt()) {
            map.put("commissionStatus", CommissionStatusEnum.Entered.toInt());
            //写入日志
            String createName = UserUtil.getCurrentUser().getUsername();
            Date createTime = new Date();
            erpOrderLogService.insertOrderLog(orderNo, "erp订单修改提成核算状态" + ' ' + createName + ' ' + createTime);
        }
        if (erpOrderEntity.getCommissionStatus() == CommissionStatusEnum.Entered.toInt()) {
            map.put("commissionStatus", CommissionStatusEnum.NOTENTERED.toInt());
            //写入日志
            String createName = UserUtil.getCurrentUser().getUsername();
            Date createTime = new Date();
            erpOrderLogService.insertOrderLog(orderNo, "erp订单修改提成核算状态" + ' ' + createName + ' ' + createTime);
        }
        baseMapper.updateByMap(map, orderNo);
        return R.ok();
    }

    /**
     * ErpOrderServiceImpl
     * 批量审核
     * 紫云网提成核算 OrderRoyaltyController
     *
     * @param
     * @return
     */
    public R toBatchAudit(String ids) {
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<String> idList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            idList.add(split[i]);
        }
        List<ErpOrderEntity> orderEntityList = this.selectBatchIds(list);
        //判断是否所有订单都为已完成
        for (int i = 0; i < orderEntityList.size(); i++) {
            if (orderEntityList.get(i).getCommissionStatus() != CommissionStatusEnum.Entered.toInt()) {
                return R.error("请检查所选订单提成状态是否均为 已录入!");
            }
        } //判断是否所有订单都为已完成
        for (int i = 0; i < orderEntityList.size(); i++) {
            if (orderEntityList.get(i).getProductionStatus() != ProductionStatusEnum.FINISH.toInt()) {
                return R.error("请检查所选订单生产状态是否均为已完成状态!只有已完成才能进行成本录入");
            }
        }
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("commissionStatus", CommissionStatusEnum.SETTLED.toInt());
        baseMapper.batchAudit(updateMap, idList); //应用已有的方法batchAudit
        //写入日志
        for (ErpOrderEntity erpOrder : orderEntityList) {
            String orderNo = erpOrder.getOrderNo();
            String createName = UserUtil.getCurrentUser().getUsername();
            Date createTime = new Date();
            erpOrderLogService.insertOrderLog(orderNo, "erp订单修改提成核算状态" + ' ' + createName + ' ' + createTime);
        }
        return R.ok();
    }

    @Override
    public void synPayInfo() {
        baseMapper.synPayInfo();
    }

}
